/**
 * 项目名称: Topic_109.cpp
 * 项目路径: study/DataStructure/LeetCode/树/中等
 * 编辑时间: 2024年08月27日07时47分52秒
 * 用   户: 轻尘
 */

#include <bits/stdc++.h>

using namespace std;

struct ListNode {
    int val;
    ListNode *next;

    ListNode() : val(0), next(nullptr) {}

    ListNode(int x) : val(x), next(nullptr) {}

    ListNode(int x, ListNode *next) : val(x), next(next) {}
};

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;

    TreeNode() : val(0), left(nullptr), right(nullptr) {}

    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}

    TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    void insertNode(TreeNode *&T, vector<int>vn,int left,int right) {
        if(left > right)return;
        int mid = (left+right)/2;
        T= new TreeNode;
        T->val = vn[mid];
        insertNode(T->left,vn,left,mid-1);
        insertNode(T->right,vn,mid+1,right);
    }

    TreeNode *sortedListToBST(ListNode *head) {
        if(!head) return nullptr;
        TreeNode * T;
        ListNode * p=head;
        vector<int>vn;
        while (p){
            vn.push_back(p->val);
            p=p->next;
        }

        insertNode(T,vn,0,vn.size()-1);
        return T;
    }
};